//
//  SearchResultController.swift
//  ReadingNow
//
//  Created by iOS Developer on 2017/6/20.
//  Copyright © 2017年 lig. All rights reserved.
//

import UIKit
import Alamofire
import Kanna
import Kingfisher
class SearchResultController: UITableViewController {
    var searchContent = ""
    var bookURLs = [String]()
    var BookCellContentCache = [Int:BookCellContent]()
    override func viewDidLoad() {
        super.viewDidLoad()
        loadBooks()
    }
    func loadBooks(){
        title = "搜索中"
        Alamofire.request("http://zhannei.baidu.com/api/customsearch/searchwap?q=\(searchContent.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)&s=920895234054625192").responseData(queue: .main) {[weak self] resp in
            if resp.result.isSuccess {
                if let books = resp.result.value, let json = try? JSON(data: books) {
                    self?.bookURLs = json["results"].arrayValue.map{
                        $0["url"].stringValue.replacingOccurrences(of: "www", with: "m")
                    }
                    self?.title = "搜索结果"
                }
            }else {
                self?.title = "搜索失败"
                let alert = UIAlertController(title: "提示", message: resp.result.error?.localizedDescription, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "确定", style: .default))
                self?.present(alert, animated: true)
            }
            if let sself = self {
                sself.title = "搜索中"
                Alamofire.request("http://zhannei.baidu.com/api/customsearch/searchwap?q=\(sself.searchContent.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)&s=13603361664978768713").responseData(queue: .main) {[weak self] resp in
                    if resp.result.isSuccess {
                        if let books = resp.result.value, let json = try? JSON(data: books) {
                            self?.bookURLs.append(contentsOf: json["results"].arrayValue.map{
                                $0["url"].stringValue.replacingOccurrences(of: "www", with: "m")
                            })
                            self?.tableView.reloadData()
                            self?.title = "搜索结果"
                        }
                    }else {
                        self?.title = "搜索失败"
                        let alert = UIAlertController(title: "提示", message: resp.result.error?.localizedDescription, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "确定", style: .default))
                        self?.present(alert, animated: true)
                    }
                }
            }
        }
    }
    
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        if bookURLs.count == 0 {
            tableView.separatorStyle = .none
        }else {
            tableView.separatorStyle = .singleLine
        }
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return bookURLs.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "book cell", for: indexPath) as! BookTableViewCell
        cell.nameAuther.text = "";cell.lastUpdateTime.text = "";
        cell.lastChapter.setTitle("", for: .normal)
        cell.lastChapter.isUserInteractionEnabled = false
        cell.isUserInteractionEnabled = false
        //chech weather has local cache
        if let cellCache = BookCellContentCache[indexPath.row] {
            cell.nameAuther.text = cellCache.name + "\t" + cellCache.author
            cell.lastUpdateTime.text = cellCache.time
            cell.lastChapter.setTitle( cellCache.chapter, for: .normal)
            cell.lastChapter.latestedPath = cellCache.url
            cell.bookHeader.kf.setImage(with: URL(string: cellCache.img))
            cell.lastChapter.isUserInteractionEnabled = true
            cell.isUserInteractionEnabled = true
            cell.latestedTen = cellCache.latestedTen
            cell.allChapters = cellCache.all
            cell.orign.text = cellCache.host
        }else {
            //load data from net
            Alamofire.request(bookURLs[indexPath.row]).responseData(queue: DispatchQueue.main) {[weak weakSelf = self] resp in
                if let data = resp.result.value {
                    if let doc = HTML(html: data, encoding: .utf8), let dhost = resp.response?.url?.host {
                        cell.orign.text = dhost
                        if dhost == "m.qu.la" {
                            let _name = doc.xpath("//span[@class='title']").first?.text ?? ""
                            let _author = doc.xpath("//div[@class='synopsisArea_detail']/a[position()=1]/p").first?.text ?? ""
                            let _time = doc.xpath("//div[@class='synopsisArea_detail']/p[position()=3]").first?.text ?? ""
                            let _chapter = doc.xpath("//div[@class='synopsisArea_detail']/p[position()=4]/a").first?.text ?? ""
                            let _url = doc.xpath("//div[@class='synopsisArea_detail']/p[position()=4]/a").first?["href"] ?? ""
                            let _img = doc.xpath("//div[@class='synopsisArea_detail']/img").first?["src"] ?? ""
                            let _all = doc.xpath("//a[@id='AllChapterList']").first?["href"] ?? ""
                            cell.nameAuther.text = _name + "\t" + _author
                            cell.lastUpdateTime.text = _time.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                            cell.lastChapter.setTitle( _chapter, for: .normal)
                            cell.lastChapter.latestedPath = "http://\(dhost)/" + _url
                            cell.bookHeader.kf.setImage(with: URL(string: _img))
                            cell.lastChapter.isUserInteractionEnabled = true
                            cell.isUserInteractionEnabled = true
                            cell.latestedTen.removeAll()
                            for chapter in doc.xpath("//div[@class='directoryArea']//a") {
                                cell.latestedTen.append((chapter.text!,"http://\(dhost)/" + chapter["href"]!))
                            }
                            cell.allChapters = "http://\(dhost)/" + _all
                            weakSelf?.BookCellContentCache[indexPath.row] = BookCellContent(name: _name, author: _author, time: cell.lastUpdateTime.text, chapter: _chapter, url: cell.lastChapter.latestedPath, img: _img, all: cell.allChapters, latestedTen: cell.latestedTen, host: dhost)
                        }else if dhost == "m.biqudu.com" {
                            let _name = doc.xpath("//div[@class='block_txt2']/p[position()=1]").first?.text ?? ""
                            let _author = doc.xpath("//div[@class='block_txt2']/p[position()=2]").first?.text ?? ""
                            let _time = doc.xpath("//div[@class='block_txt2']/p[position()=5]").first?.text ?? ""
                            let _chapter = doc.xpath("//div[@class='block_txt2']/p[position()=6]/a").first?.text ?? ""
                            let _url = doc.xpath("//div[@class='block_txt2']/p[position()=6]/a").first?["href"] ?? ""
                            let _img = doc.xpath("//div[@class='block_img2']/img").first?["src"] ?? ""
                            let _all = doc.xpath("//div[@class='intro']/a").first?["href"] ?? ""
                            cell.nameAuther.text = _name + "\t" + _author
                            cell.lastUpdateTime.text = _time
                            cell.lastChapter.setTitle( _chapter, for: .normal)
                            cell.lastChapter.latestedPath = "http://\(dhost)/" + _url
                            cell.bookHeader.kf.setImage(with: URL(string: _img))
                            cell.lastChapter.isUserInteractionEnabled = true
                            cell.isUserInteractionEnabled = true
                            cell.latestedTen.removeAll()
                            for chapter in doc.xpath("//ul[@class='chapter']//a") {
                                cell.latestedTen.append((chapter.text!,"http://\(dhost)/" + chapter["href"]!))
                            }
                            cell.allChapters = "http://\(dhost)/" + _all
                            weakSelf?.BookCellContentCache[indexPath.row] = BookCellContent(name: _name, author: _author, time: _time, chapter: _chapter, url: cell.lastChapter.latestedPath, img: _img, all: cell.allChapters, latestedTen: cell.latestedTen, host: dhost)
                        }
                    }
                }else {
                    let alert = UIAlertController(title: "提示", message: "\(indexPath.row). 内容加载失败", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "确定", style: .default))
                    weakSelf?.present(alert, animated: true)
                }
            }
        }
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action = UITableViewRowAction(style: .default, title: "添加到书单") { (act, indexPath) in
            if !self.bookURLs[indexPath.row].isEmpty {
                let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
                let documentDirectory = paths[0] as! String
                let path = documentDirectory.appending("/urls.plist")
                if var array = NSArray(contentsOfFile: path) as? [String]{
                    array.append(self.bookURLs[indexPath.row])
                    (array as NSArray).write(toFile: path, atomically: false)
                    let alert = UIAlertController(title: "提示", message: "添加成功", preferredStyle: .alert)
                    self.present(alert, animated: true){
                        alert.dismiss(animated: true)
                        tableView.isEditing = false
                    }
                }
            }else{
                let alert = UIAlertController(title: "提示", message: "无法添加", preferredStyle: .alert)
                self.present(alert, animated: true){
                    alert.dismiss(animated: true)
                }
            }
            
        }
        action.backgroundColor = .darkGray
        return [action]
    }
    
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //segue id 'latest ten' and 'loadContent'
        if segue.identifier == "latest ten",let cell = sender as? BookTableViewCell {
            let dest = segue.destination as! LastTenTableViewController
            dest.tenChapters = cell.latestedTen
            dest.allChapters = cell.allChapters
        }else if segue.identifier == "loadContent", let dest = segue.destination as? ContentViewController ,let btn = sender as? ChapterButton {
            dest.contentURL = btn.latestedPath
        }
    }
    
}
